import React, { Component } from "react"
import InfoTable from "../common/sourceTable"
import { Card, Button, Popconfirm, message, Switch } from "antd"
import { FormInstance } from 'antd/lib/form'
import { EditFilled, DeleteFilled } from '@ant-design/icons'
import { getUserInfo, addtUserInfo, editUserInfo, delUserInfo, editUserSta } from "@net/user/index"
import { getRoleInfo } from "@net/role/index"
import DialogForm from '../common/dialogForm'
import Modal from '@comp/Modal'
import HeaderSearch from '../common/headerSearch'
import Power from '@comm/power'
import md5 from 'blueimp-md5'
import "../../index.scss"

interface IPorps { }
interface IStates {
    data: any[]
    loading: boolean,
    popVisible: string,
    visible: boolean,
    title: string,
    delId: number,
    editId: number,
    roleSelectData: any[],
    page: number,
    pageSize: number,
    total: number,
    search: any
}

export default class UserInfo extends Component<IPorps, IStates> {
    private dialogFormRef = React.createRef<FormInstance>() as any
    // 表格设置
    private column = [
        {
            key: "name",
            dataIndex: "name",
            title: "用户名称",
            align: "center"
        },
        {
            key: "userName",
            dataIndex: "userName",
            title: "用户账户",
            align: "center"
        },
        {
            key: "email",
            dataIndex: "email",
            title: "用户邮箱",
            align: "center"
        },
        {
            key: "role",
            dataIndex: "role",
            title: "用户角色",
            align: "center"
        },
        {
            key: "status",
            dataIndex: "status",
            title: "用户状态",
            align: "center",
            render: (text: string, record: any) => {
                // if (text === "0") { return <Button type="link">已锁定</Button> }
                // else if (text === "1") { return <Button type="link" className="agree">正常</Button> }
                let isChecked: boolean
                text === "0" ? isChecked = false : isChecked = true
                return (
                    <Power authKey="user:user:status">
                        <Switch
                            checkedChildren="锁定"
                            unCheckedChildren="解锁"
                            checked={isChecked}
                            size="small"
                            onChange={() => { this.editUserSta(record) }} />
                    </Power>
                )
            }
        },
        {
            key: "createtime",
            dataIndex: "createtime",
            title: "注册时间",
            align: "center"
        },
        {
            key: "do",
            dataIndex: "do",
            title: "操作",
            align: "center",
            render: (text: any, record: any) => {
                const item = record
                return (
                    <div className="do">
                        <Power authKey="user:user:update">
                            <Button size="small" type="primary" icon={<EditFilled />} onClick={() => { this.openEditDia(item) }} />
                        </Power>
                        <Power authKey="user:user:remove">
                            <Popconfirm title="您确定要删除吗？" okText="是" cancelText="否"
                                onConfirm={this.delete} visible={item.key === this.state.popVisible}
                                onCancel={() => { this.setState({ popVisible: "-1" }) }}>
                                <Button size="small" danger icon={<DeleteFilled />} onClick={() => { this.openPopDia(item) }} />
                            </Popconfirm>
                        </Power>
                    </div>
                )
            }
        }
    ]
    private dialogFormCol = () => {
        return [
            {
                type: 'input',
                label: "用户名称",
                name: "name",
                rules: [
                    { required: true, message: "请输入名称" }
                ],
                component: {
                    placeholder: "请输入名称",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "账户",
                name: "userName",
                rules: [
                    { required: true, message: "请输入账户" }
                ],
                component: {
                    placeholder: "请输入账户",
                    disabled: this.state.title === "用户信息添加" ? false : true
                },
                style: { borderRadius: "5px" }
            },
            this.state.title === '用户信息添加' ?
                {
                    type: 'password',
                    label: "密码",
                    name: "passWord",
                    rules: [
                        { required: true, message: "请输入密码" }
                    ],
                    component: {
                        placeholder: "请输入密码",
                    },
                    style: { borderRadius: "5px" }
                } :
                { type: "none" },
            {
                type: 'input',
                label: "邮箱",
                name: "email",
                rules: [
                    { required: true, message: "请输入邮箱", type: "email" }
                ],
                component: {
                    placeholder: "请输入账户",
                    disabled: this.state.title === "用户信息添加" ? false : true
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'select',
                label: "角色",
                name: "role",
                option: this.state.roleSelectData,
                rules: [
                    { required: true, message: "请选择用户角色" }
                ],
                component: {
                    placeholder: "请选择用户角色",
                },
                style: { borderRadius: "5px" }
            },
            this.state.title === "用户信息编辑" ?
                {
                    type: 'select',
                    label: "状态",
                    name: "status",
                    option: [{ key: "0", value: "锁定" }, { key: "1", value: "正常" }],
                    rules: [
                        { required: true, message: "请选择用户角色" }
                    ],
                    component: {
                        placeholder: "请选择用户角色",
                    },
                    style: { borderRadius: "5px" }
                } : { type: "none" },
        ]
    }
    private searchCol = [
        {
            type: 'input',
            name: "name",
            label: "用户名称",
            component: {
                placeholder: "请输入用户名称",
            },
            style: { borderRadius: "5px" }
        },
        {
            type: 'select',
            name: "status",
            label: "用户状态",
            option: [
                { value: "锁定", key: "0" },
                { value: "正常", key: "1" }
            ],
            component: {
                placeholder: "请选择用户状态",
            },
            style: { borderRadius: "5px", width: "200px" }
        }
    ]
    constructor(props: IPorps) {
        super(props)
        this.state = {
            data: [],
            loading: true,
            popVisible: "-1",
            visible: false,
            title: "",
            delId: 0,
            editId: 0,
            roleSelectData: [],
            page: 1,
            pageSize: 5,
            total: 0,
            search: null
        }
    }
    public componentDidMount() {
        this.fetchData(this.state.page, this.state.pageSize)
        getRoleInfo({ page: 1 },null).then((res: any) => {
            res.data.data.forEach((item: any) => {
                item.lalel = item.name
                item.value = item.name
            });
            this.setState({ roleSelectData: res.data.data })
        })
    }
    // 用户解锁与锁定
    public editUserSta = async (item: any) => {
        if (item.status === "0") {
            item.status = "1"
            const res = await editUserSta("1", item.Id)
            const { status, msg } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.fetchData(this.state.page, this.state.pageSize)
            }
        } else {
            item.status = "0"
            const res = await editUserSta("0", item.Id)
            const { status, msg } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.fetchData(this.state.page, this.state.pageSize)
            }
        }
    }
    // 获取数据
    public fetchData = async (page: number, pageSize: number) => {
        let res
        res = await getUserInfo({ page, pageSize }, this.state.search)
        res.data.data.map((item: any) => {
            return item.key = item.Id
        })
        this.setState({ loading: false, data: res.data.data, total: res.data.total })
    }
    public search = (item: any) => {
        if (item.name === undefined && item.status === undefined) {
            this.setState({ search: null },() => {
                this.fetchData(this.state.page, this.state.pageSize)
            })
            return
        } else {
            this.setState({ search: item }, async () => {
                const res = await getUserInfo({ page: 1, pageSize: 5 }, item)
                const { status, msg, data, total } = res.data
                if (status === 203) {
                    message.error({ content: msg, style: { marginTop: "20%" } })
                } else {
                    message.success({ content: msg, style: { marginTop: "20%" } })
                    this.setState({ data: data, total: total })
                }
            })
        }
    }
    // 页码切换监听事件
    public pageChange = (page: number, pageSize?: number) => {
        if (pageSize) {
            this.setState({ page, pageSize }, () => {
                this.fetchData(page, pageSize)
            })
        }
    }
    // 打开对话框
    public openAddDialog = () => {
        this.setState({ visible: true, title: "用户信息添加" })
    }
    public openEditDia = (item: any) => {
        this.setState({ visible: true, title: "用户信息编辑", editId: item.Id }, () => {
            this.dialogFormRef.current.setFieldsValue(item)
        })
    }
    public openPopDia = (item: any) => {
        this.setState({ popVisible: item.key, delId: item.Id })
    }
    // 点击对话框确认事件
    public onAddOk = () => {
        this.dialogFormRef.current.validateFields(this.add())
    }
    public onEditOk = () => {
        this.dialogFormRef.current.validateFields(this.edit())
    }
    public add = () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        values.passWord = md5(values.passWord)
        if (values.userName === undefined || values.passWord === undefined || values.email === undefined || values.role === undefined) {
            return
        } else {
            addtUserInfo(values).then((res: any) => {
                const { msg, status } = res.data
                if (status === 203) {
                    message.error({ content: msg, style: { marginTop: "20%" } })
                } else if (status === 200) {
                    message.success({ content: msg, style: { marginTop: "20%" } })
                    this.cancel()
                    this.fetchData(this.state.page, this.state.pageSize)
                }
            })
        }
    }
    public edit = async () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        values.Id = this.state.editId
        const res = await editUserInfo(values)
        const { status, msg } = res.data
        if (status === 203) {
            message.error({ content: msg, style: { marginTop: "20%" } })
        } else if (status === 200) {
            message.success({ content: msg, style: { marginTop: "20%" } })
            this.cancel()
            this.fetchData(this.state.page, this.state.pageSize)
        }
    }
    public delete = async () => {
        const res = await delUserInfo(this.state.delId)
        const { status, msg } = res.data
        if (status === 203) {
            message.error({ content: msg, style: { marginTop: "20%" } })
        } else if (status === 200) {
            message.success({ content: msg, style: { marginTop: "20%" } })
            this.setState({ popVisible: "-1" })
            this.fetchData(this.state.page, this.state.pageSize)
        }
    }
    public cancel = () => {
        this.setState({ visible: false })
        this.dialogFormRef.current.resetFields()
    }
    public getContent = () => {
        return (
            <DialogForm ref={this.dialogFormRef} column={this.dialogFormCol()} go={() => { }}></DialogForm>
        )
    }
    public renderModal = (item?: string) => {
        return (<Modal
            title={this.state.title}
            visible={this.state.visible}
            content={this.getContent()}
            onOk={item === "" ? this.onAddOk : this.onEditOk}
            onCancel={this.cancel}></Modal>)
    }
    public renderButton() {
        return (
            <div>
                <Power authKey="user:user:save">
                    <Button type="primary" onClick={this.openAddDialog}>新增用户</Button>
                </Power>
            </div>
        )
    }
    public render() {
        const { total } = this.state
        return (
            <div className="source">
                <Card className="card">
                    <HeaderSearch
                        authKey="user:user:list"
                        column={this.searchCol}
                        search={this.search}></HeaderSearch>
                    {this.renderButton()}
                    <InfoTable
                        columns={this.column}
                        loading={this.state.loading}
                        dataSource={this.state.data}
                        pageChange={this.pageChange}
                        total={total}>
                    </InfoTable>
                </Card>
                {this.state.title === "用户信息添加" ? this.renderModal("") : this.renderModal()}
            </div>
        )
    }
}